<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;

class OrderGroup extends Model
{
    // 表名
    protected $name = 'order_group';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text',
        'finish_time_text',
	    'status_text'
    ];
    
	const STATUS_W = 0;
	const STATUS_Y = 1;
	const STATUS_D = 2;
	   
	public static $statusList = [
		self::STATUS_Y => '已成团',
		self::STATUS_W => '拼团中',
		self::STATUS_D => '拼团失败'
	];

	public function getStatusTextAttr($value, $data) {
		$value = $value ? $value : $data['status'];
		$list = self::$statusList;
		return isset($list[$value]) ? $list[$value] : '';
	}

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['update_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getFinishTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['finish_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setFinishTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
    
    
    public function goods(){
		return $this->belongsTo('goods', 'goods_id', 'id', '', 'left')->setEagerlyType(0);
    }


    public function changeNumber($orderData, $goodsId) {
		if($orderData['order_group_id']) {
			$row = Db::name('orderGroup')->find($orderData['order_group_id']);
			if(!$row) {
				return true;
			}
			
			$data['buy_number'] = $row['buy_number'] +1;
			if($data['buy_number'] >= $row['limit_number']) {
				$data['status'] = self::STATUS_Y;
				$data['finish_time'] = time();
				
				//更改这个团的订单为已待发货
				$orderModel = new Order();
				$orderRes = $orderModel
					->save(['order_status' => $orderModel::STATUS_WAIT_DELIVERY], ['order_group_id' => $orderData['order_group_id']]);
				if(!$orderRes) {
					$this->error = '更改订单状态出错';
					return false;
				}
			}
			$res = $this->save($data,['id' => $orderData['order_group_id']]);
			
		} else {
			
			//查找拼团商品记录
			$row = Db::name('goodsGroup')
				->where(['goods_id' => $goodsId])
				->find();
			
			$res = $this->isUpdate(false)	->save([
				'user_id' => $orderData['user_id'],
                'goods_group_id' => $row['id'],
                'goods_id' => $goodsId,
				'limit_number' => $row['number'],
				'buy_number' => 1,
				'end_time' => time()+$row['limit_minute']*3600,
			]);
			
			$groupId = $this->getLastInsID();
			//更改这个团的订单为已待发货
			$orderModel = new Order();
			$orderRes = $orderModel
				->save(['order_group_id' => $groupId], ['id' => $orderData['id']]);
			if(!$orderRes) {
				$this->error = '更改订单拼团ID出错';
				return false;
			}
		}
		
		if(!$res) {
			$this->error = '操作拼团记录出错';
			return false;
		}
		
		return true;
    }
	
	/**
	 * 处理超时的拼团订单
	 * @return bool
	 * @throws \think\exception\PDOException
	 */
    public function checkGroupOrder(){
	    $orders = $this
		    ->where(['status' => self::STATUS_W, 'end_time' => ['lt', time()]])
		    ->column('user_id', 'id');
	    if(!$orders) {
	    	$this->error = '没有拼团超时的订单'. $this->getLastSql();
	    	return true;
	    }
	    
	    $this->startTrans();
	    try {
	    	//拼团失败的ID
	    	$groupIds = array_keys($orders);
	    	
	    	//更改拼团状态
		    $groupRes = $this->save(['status' => self::STATUS_D], ['id' => ['in', $groupIds]]);
		    if(!$groupRes) {
		    	throw new Exception('更改拼团记录状态出错');
		    }
		    
		    $orderModel = new Order();
		    
		    $orders = $orderModel->where(['order_group_id' => ['in', $groupIds]])->select();
		    if($orders) {
			    //更改订单状态为拼团失败
			    $orderRes = $orderModel->save(
				    ['order_status' => $orderModel::STATUS_CLOSE, 'close_type' => $orderModel::CLOSE_TYPE_TIMEOUT],
				    ['order_group_id' => ['in', $groupIds]]
			    );
			
			    if(!$orderRes) {
				    throw new Exception('更改订单状态出错');
			    }
			
			    $logModel = new FundsRecord();
			    $couponModel = new UserCoupon();
			    //给用户退款,退优惠券
			    foreach ($orders as $order) {
			        //支付成功的才退款，积分支付退回积分，其它到余额
			        if($order['pay_status'] == $orderModel::PAY_STATUS_Y && $order['order_amount'] > 0) {
				
				        $user = Db::name('user')->find($order['user_id']);
			        	if($order['pay_type'] == Payment::PAY_TYPE_POINT) {
			        		
			        	    $userRes = Db::name('user')
					            ->where(['id' => $order['user_id']])
					            ->setInc('integral', $order['order_amount']);
			        	    
			        	    if(!$userRes) {
			        	        throw new Exception('添加用户积分出错');
				            }
				            
				            $logRes = $logModel->addRecord($order['user_id'], $order['order_amount'], $user['integral'], $logModel::ACCOUNT_TYPE_INTEGRAL, $logModel::OPE_TYPE_PLUS, $logModel::TYPE_ORDER_REBACK, $order['id'], '拼团失败退款');
			        	    if(!$logRes) {
			        	    	throw new Exception('添加积分流水出错');
				            }
				            
				        } else {
					        $userRes = Db::name('user')
						        ->where(['id' => $order['user_id']])
						        ->setInc('balance', $order['order_amount']);
					
					        if(!$userRes) {
						        throw new Exception('添加用户余额出错');
					        }
					
					        $logRes = $logModel->addRecord($order['user_id'], $order['order_amount'], $user['balance'], $logModel::ACCOUNT_TYPE_BALANCE, $logModel::OPE_TYPE_PLUS, $logModel::TYPE_ORDER_REBACK, $order['id'], '拼团失败退款');
					        if(!$logRes) {
						        throw new Exception('添加余额流水出错');
					        }
				        }
				        
				        //如果有使用优惠券，退还优惠券
				        if($order['coupon_price'] > 0) {
				            $res = $couponModel->reback($order['di']);
				            if(!$res) {
				            	throw new Exception($couponModel->getError());
				            }
				        }
			        }
			    }
		    }
	    	
	    	$this->commit();
	    	$this->error = '处理拼团超时订单'.count($orders).'个';
	    	return true;
	    	
	    } catch (Exception $e) {
	    	$this->rollback();
	    	$this->error = $e->getMessage();
	    	return false;
	    }
    }
}
